export function dragBind(dragBox, moveBox = dragBox) {
  dragBox.onmousedown = (e) => {
    var disX = e.clientX - moveBox.offsetLeft;
    var disY = e.clientY - moveBox.offsetTop;
    document.onmousemove = (e) => {
      e.preventDefault();
      var l = e.clientX - disX;
      var t = e.clientY - disY;
      var x = document.documentElement.clientWidth - moveBox.offsetWidth;
      var y = document.documentElement.clientHeight - moveBox.offsetHeight;
      l = l < 0 ? 0 : l > x ? x : l;
      t = t < 0 ? 0 : t > y ? y : t;
      moveBox.style.left = l < 0 ? 0 : l + "px";
      moveBox.style.top = t < 0 ? 0 : t + "px";
      return false;
    };
    document.onmouseup = () => {
      document.onmousemove = null;
      document.onmouseup = null;
      return false;
    };
    return false;
  };
}

//增加事件监听
export function clickblank(dom, callback) {
  dom.addEventListener("click", callback);
}

//移除监听
export function clickremove(dom, callback) {
  dom.removeEventListener("click", callback);
}

export function uuid() {
  var temp_url = URL.createObjectURL(new Blob());
  var uuid = temp_url.toString();
  URL.revokeObjectURL(temp_url);
  return uuid.substr(uuid.lastIndexOf("/") + 1);
}

export function getHtml(option) {
  const { custome, Vue, uuid, subData } = option;
  if (!custome) {
    return "";
  }
  var targetType = custome.constructor.name;
  switch (targetType) {
    case "String":
      return ` <div>${custome}</div>`;
    case "Object":
      Vue.component("com-" + uuid, custome);
      if (subData) {
        return `<com-${uuid} :subData='subData'  />`;
      }
      return `<com-${uuid} />`;
    default:
      return custome.outerHTML;
  }
}

export function getheadHtml(option) {
  const { hasHead, customHead, title, uuid, Vue } = option;
  if (hasHead) {
    if (customHead) {
      return headTemplate(
        getHtml({ custome: customHead, uuid: uuid + "_h", Vue: Vue })
      );
    }
    var titlehtml = `<div class='titleText'>${title}</div>`;
    var head =
      titlehtml +
      `<div class='operation'>${(option.hasMin ? getminHtml() : "") +
      (option.hasMax ? getmaxHtml() : "") +
      getresetHtml() +
      getcloseHtml()}</div>`;

    return headTemplate(head);
  }
  return "";
}

//获取弹框体
export function getbodyHtml(option) {
  const { content, uuid, subData, Vue } = option;
  return bodyTemplate(
    getHtml({ custome: content, uuid: uuid + "_b", subData: subData, Vue: Vue })
  );
}

//闭包环境
var dataUtils = (function () {
  var all_nums = 0;
  var min_nums = 0;
  var baseNum = 999;
  var allLayers = {};
  return {
    addLayer(key, value) {
      allLayers[key] = value;
    },
    deleteLayer(key) {
      delete allLayers[key];
    },
    deleteAll() {
      for (var id in allLayers) {
        var parent = allLayers[id].parentNode;
        if (parent) {
          parent.removeChild(allLayers[id]);
        }
      }
      all_nums = 0;
      min_nums = 0;
      baseNum = 999;
      allLayers = {};
    },
    getminNum() {
      return min_nums;
    },
    addminNum() {
      min_nums++;
    },
    minusminNum() {
      min_nums--;
    },

    getallNum() {
      return all_nums + baseNum;
    },
    addallNum() {
      all_nums++;
    },
    minusallNum() {
      all_nums--;
    },
    getLayers() {
      var layers = document.getElementsByClassName("player");
      return layers;
    },
  };
})();

export { dataUtils };

export function vueAttribute(option) {
  var mixin = option.mixin || {};
  var vueAttr = {
    data() {
      return {
        ismin: false, //是否最小化
        ismax: false,
        lastState: {
          left: 0,
          top: 0,
          with: 0,
          height: 0,
        },
        ...option,
      };
    },
    computed: {
      canmin() {
        return this.hasMin && !this.ismin && !this.ismax;
      },
      canmax() {
        return this.hasMax && !this.ismax && !this.ismin;
      },
      canreset() {
        return this.ismin || this.ismax;
      },
    },
    beforeCreate() {
      if (!option.multiple) {
        dataUtils.deleteAll();
      }
      console.log("layer----beforeCreate");
    },
    created() {
      console.log("layer----created");
      dataUtils.addallNum();
      if (typeof this.success == "function") {
        this.success();
      }
    },
    mounted() {
      this.$nextTick(() => {
        this.resetZ(); //设置Z值
        this.resetarea(); //设置弹框大小
        this.autosize(); //水平垂直居中
        this.resetlocation(); //位置设置
        this.getLastState(); //记录位置状态
        if (this.move && this.hasHead) {
          dragBind(this.$refs.title, this.$refs.player);
          this.$refs.title.style.cursor = "move";
        }
        if (this.shade && this.blank) {
          this.stopPropagation(); //阻止事件冒泡
          clickblank(this.$refs.pshade, this.close);
        }
        dataUtils.addLayer(this.uuid, this.$refs.player);
        console.log("layer----mounted");
      });
    },
    //销毁前
    beforeDestroy() {
      if (this.shade && this.blank) {
        clickremove(this.$refs.pshade, this.close);
      }

      if (typeof this.cancel == "function") {
        this.cancel();
      }
      dataUtils.deleteLayer(this.uuid);
    },
    methods: {
      //阻止事件冒泡
      stopPropagation() {
        this.$refs.player.onclick = function (event) {
          //兼容IE低版本
          event.stopPropagation();
          event.cancelBubble = true;
        };
        if (this.hasHead) {
          this.$refs.title.onclick = function (event) {
            //兼容IE低版本
            event.stopPropagation();
            event.cancelBubble = true;
          };
        }
        this.$refs.layerbody.onclick = function (event) {
          //兼容IE低版本
          event.stopPropagation();
          event.cancelBubble = true;
        };
      },
      resetZ() {
        if (this.shade) {
          this.$refs.pshade.style["z-index"] = dataUtils.getallNum();
          dataUtils.addallNum();
        }
        this.$refs.player &&
          (this.$refs.player.style["z-index"] = dataUtils.getallNum());
        this.$refs.title &&
          (this.$refs.title.style["z-index"] = dataUtils.getallNum());
        this.$refs.layerbody &&
          (this.$refs.layerbody.style["z-index"] = dataUtils.getallNum());
      },
      //屏幕水平垂直居中
      autosize() {
        var dom = this.$refs.player;
        var CHeight = document.documentElement.clientHeight;
        var CWidth = document.documentElement.clientWidth;
        var PHeight = dom.offsetHeight;
        var PWidth = dom.offsetWidth;
        dom.style.top =
          (CHeight > PHeight ? (CHeight - PHeight) / 2 : 0) + "px";
        dom.style.left = (CWidth - PWidth) / 2 + "px";
      },
      //设置大小
      resetarea(area) {
        area = area || this.area;
        this.$refs.player.style.width = area.width;
        this.$refs.player.style.height = area.height;
      },
      //位置设置
      resetlocation(location) {
        location = location || this.location;
        if (location.top && location.left) {
          this.$refs.player.style.bottom = null;
          this.$refs.player.style.right = null;
          this.$refs.player.style.top = location.top;
          this.$refs.player.style.left = location.left;
          return;
        }
        if (location.bottom && location.right) {
          this.$refs.player.style.top = null;
          this.$refs.player.style.left = null;
          this.$refs.player.style.bottom = location.bottom;
          this.$refs.player.style.right = location.right;
        }
      },
      getLastState() {
        var innerbox = this.$refs.player;
        var innerBoxWidth = innerbox.offsetWidth; // 获取弹框宽度
        var innerBoxHeight = innerbox.offsetHeight; // 获取弹框高度
        var innerBoxLeft = innerbox.offsetLeft; // 获取弹框距离左侧宽度
        var innerBoxTop = innerbox.offsetTop; // 获取弹框距离顶部高度
        this.lastState.left = innerBoxLeft;
        this.lastState.top = innerBoxTop;
        this.lastState.with = innerBoxWidth;
        this.lastState.height = innerBoxHeight;
      },

      initState(state) {
        state = state || this.lastState;
        this.$refs.player.style.right = "auto";
        this.$refs.player.style.bottom = "auto";
        this.$refs.player.style.top = state.top + "px";
        this.$refs.player.style.left = state.left + "px";
        this.$refs.player.style.width = state.with + "px";
        this.$refs.player.style.height = state.height + "px";
      },
      //最小化
      min() {
        console.log("layer----min");
        this.getLastState();
        // var mincount = dataUtils.getminNum();
        // var win_width = document.documentElement.clientWidth;
        // var max_col = Math.floor(win_width / this.minWidth);
        // var row = Math.floor(mincount / max_col);
        // this.$refs.player.style.top = "auto";
        // this.$refs.player.style.right = "auto";
        // this.$refs.player.style.bottom =
        //   this.bottomOff + row * (this.minHight + this.rowGap) + "px";
        // this.$refs.player.style.left =
        //   this.leftOff +
        //   (mincount - row * max_col) * (this.minWidth + this.colGap) +
        //   "px";
        this.$refs.player.style.width = this.minWidth + "px";
        this.$refs.player.style.height = this.minHight + "px";
        this.$refs.layerbody.style.display = "none";
        this.ismin = true;
        dataUtils.addminNum();
        this.$refs.player.setAttribute("ismin", true);
        // if (dataUtils.getminNum() > 1) {
        //   this.updateLayers();
        // }

        //更新位置
        this.updateLayers();

        if (typeof this.minBack == "function") {
          this.minBack();
        }
      },
      updateLayers() {
        var layers = dataUtils.getLayers();
        var mincount = 0;
        var win_width = document.documentElement.clientWidth;
        var max_col = Math.floor((win_width-this.leftOff) / this.minWidth);
        for (var j = 0, len = layers.length; j < len; j++) {
          if (layers[j].getAttribute("ismin")) {
            var row = Math.floor(mincount / max_col);
            layers[j].style.top = "auto";
            layers[j].style.right = "auto";
            layers[j].style.bottom =
              this.bottomOff + row * (this.minHight + this.rowGap) + "px";
            layers[j].style.left =
              this.leftOff +
              (mincount - row * max_col) * (this.minWidth + this.colGap) +
              "px";
            mincount++;
          }
        }
      },
      max() {
        console.log("layer----max");
        this.getLastState();
        this.$refs.player.style.top = 0 + "px";
        this.$refs.player.style.left = 0 + "px";
        this.$refs.player.style.width = "100%";
        this.$refs.player.style.height = "100%";
        this.ismax = true;
        if (typeof this.maxBack == "function") {
          this.maxBack();
        }
      },
      reset() {
        console.log("layer----reset");
        if (this.ismin) {
          dataUtils.minusminNum();
          this.$refs.layerbody.style.display = "block";
        }
        this.initState();
        this.ismin = false;
        this.ismax = false;
        this.$refs.player.setAttribute("ismin", false);
        if (typeof this.restore == "function") {
          this.restore();
        }
      },
      close() {
        var parent = this.$refs.player.parentNode;
        if (parent) {
          parent.removeChild(this.$refs.player);
          dataUtils.deleteLayer(this.uuid);
        }
        this.$destroy();
        console.log("layer----close");
      },
    },
    mixins: [mixin],
  };
  return vueAttr;
}

//头部模板
export function headTemplate(str) {
  return `
      <div  class='ptitle' ref='title'>
        ${str}
      </div>`;
}

//弹框体模板
export function bodyTemplate(str) {
  return `
      <div  class='playerbody' ref='layerbody'>
        ${str}
      </div>`;
}

//遮罩模板
export function shadeTemplate(shade) {
  return shade ? `<div class='pshade' ref='pshade' ></div>` : "";
}

//最终弹框模板
export function dialogTemplate(str) {
  return `
      <div :class='theme' class='player' ref='player'>
        ${str}
      </div>`;
}

function getminHtml() {
  return `<div class="xaMin" v-show="canmin" @click="min()"></div>`;
}

function getmaxHtml() {
  return `<div class="xaMax" v-show="canmax" @click="max()"></div>`;
}

function getresetHtml() {
  return `<div class="xaReset" v-show="canreset" @click="reset()"></div>`;
}

function getcloseHtml() {
  return `<div class="xaClose" @click="close()"></div>`;
}
